<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 麦克
 */
class MaikeController extends PayController{
    protected $config;
	protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );
		
		$data=[];
        $data['merCode'] = $this->config['mch_id'];
        $data['tranNo'] = $return['orderid'];
        $data['tranAmt'] = strval($return['amount']*100);
        $data['settleType'] = '0';

        switch($this->config['paytype']) {
            //微信
            case 1:
                $data['collectWay'] = 'WXZF';
                break;
            //微信H5
            case 2:
                $data['collectWay'] = 'WXGZH';
                break;
            //支付宝扫码
            case 3:
                $data['collectWay'] = 'APAY';
                break;
            //支付宝H5
            case 4:
                $data['collectWay'] = 'APAY';
                break;
            //支付宝扫码
            case 17:
                $data['collectWay'] = 'APAY';
                break;
            //支付宝H5
            case 18:
                $data['collectWay'] = 'APAY';
                break;
            //QQ
            case 8:
                $data['collectWay'] = 'QQZF';
                break;
            //QQH5
            case 10:
                $data['collectWay'] = 'QQWEP';
                break;
            //银联
            case 11:
                $data['collectWay'] = 'UPZF';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['tranTime'] = date("YmdHis",time());
        $data['expireTime'] = "5";
        $data['noticeUrl'] = $return['notifyurl'];
        $data['subject'] = 'pg';
        $data['orderDesc'] = 'zf';
        ksort($data);
        $str = httpstr($data).$this->config['signkey'];
        $data['sign'] = md5($str);

        $data_string =json_encode($data);

        $ch = curl_init($this->config['gateway']);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER,0 );
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                "Accept: application/json",
                "Content-Length: " . strlen($data_string),
                "Cache-Control: no-cache",
                "Pragma: no-cache")
        );
        $res = $origin = curl_exec($ch);
        curl_close($ch);

        if(!$res){
            $this->showmessage('获取数据失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $res = json_decode($res, true);

        //echo '<pre/>'; print_r($res); exit;

        $payurl = $res['URL'];

        //echo '<pre>'; print_r($payurl); echo '</pre>';

        if(!$payurl){
            if($res['respMsg']){
                $this->showmessage($res['respMsg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        switch($this->config['paytype']){
            //支付宝H5
            case 4:
            case 3:
            case 17:
            case 18:
                if(isMobile()){
                    header("location: {$payurl}");exit;
                }
            default:
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?data=".urlencode($payurl));
        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
                $this->display("WeiXin/alipay");
                break;
            //支付宝H5
            case 4:
                $this->display("WeiXin/alipay");
                break;
            //支付宝扫码
            case 17:
                $this->display("WeiXin/alipay");
                break;
            //支付宝H5
            case 18:
                $this->display("WeiXin/alipay");
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true."\r\n\r\n"), FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date('Y-m-d H:i:s',time())."\r\n\r\n", FILE_APPEND);

        $s = file_get_contents('php://input');

        //$s = '{"respCode":"0","respMsg":"交易成功","settleDate":"20180820","sign":"a17bcd9ae5701ae12a3c6731b3c8dff3","tranAmt":"1000","tranNo":"201808201913354099477"}';
        $p = $data = json_decode($s, true);
        if(!$p || empty($p)){
            exit;
        }
        //echo '<pre/>'; print_r($p);exit;
        /*
         * Array
            (
                [respCode] => 0
                [respMsg] => 交易成功
                [settleDate] => 20180820
                [sign] => a17bcd9ae5701ae12a3c6731b3c8dff3
                [tranAmt] => 1000
                [tranNo] => 201808201913354099477
            )
         */

        //获取订单信息
        $orderid = $p['tranNo'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();

        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$p['busi_order_no']))->save(array("server_return"=> $s));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>'Maike'))->find();

        if($p['respCode'] != 0){
            echo "pail_fail"; exit;
        }

        $sign = $p['sign'];
        unset($p['sign']);

        ksort($p);
        $str = httpstr($p).$this->config['signkey'];
        $sign2 = md5($str);

        //echo 'sign: '.$sign.'<br/>';
        //echo 'sign2:'.$sign2;exit;

        if($sign != $sign2){
            exit("fail");
        }

        //处理支付
        $this->EditMoney($find['pay_orderid'],"Maike",0);
        //回调成功
        echo '000000'; exit;
    }

    public function callBackUrl(){

        echo '操作成功'; exit;
    }
}